/* Copyright (c) 2009-2010, Sean A.O. Harney <sharney3@gmail.com> */

#include "omf.h"


//expects already evaled leaf expr of STRING for both args
// expr0 is path, expr1 is fopen mode (e.g. "r+") whatever underlying libc supports is supported by OMF so may vary on diff systems.

EXPR_P builtin_func_open(EXPR_P expr0, EXPR_P expr1)
{
    if (expr0->u.leaf.type != LEAF_STRING)
	fatal_error_println
	    ("OMF built-in function open() expects STRING expr as 1st argument.");

    if (expr1->u.leaf.type != LEAF_STRING)
	fatal_error_println
	    ("OMF built-in function open() expects STRING expr as 2nd argument.");


    char *str_path = expr0->u.leaf.val.string_val;
    char *str_mode = expr1->u.leaf.val.string_val;
    FILE *fp = fopen(str_path, str_mode);
    if (fp == NULL)
	fatal_error_perror("fopen()");	// NOTE: should be fatal or perhaps just return -1 so as not to end calling program?? FIXME

    int fd = fileno(fp);	// won't be losing anything since not using fread,fwrite and more to gain by allowing access to filenos as an integral number able to be stored in a type INT inside omf programs

    debug1_printf("opened %s (%s) as fileno %d.\n", str_path, str_mode,
		  fd);

    //TODO: move tihs an other copies of it to a util func.
    INTVAL_P iv = checked_malloc(sizeof(struct st_int_val));
    iv->ulong_val = fd;
    iv->negative = false;

    return new_expr_leaf_int(iv);
}
